<?php
namespace sef;
class controller {
	protected $app_name;
	protected $app_type;
	protected $view;
	protected $auth;
	protected $auth_map;
	protected $vars = array();

	function __construct() {
		$this -> app_name = str_replace('_controller', '', get_class($this));
		$this -> view = new view();		
				
		if (method_exists($this, 'init')) {
			$this -> init();
		}

		$this -> auth = new auth($this -> app_type, $this -> auth_map);
		if (!$this -> auth -> status) {
			$this -> error('没有权限');
		}
	}

	protected function assign($key, $val) {
		$this -> vars[$key] = $val;
	}

	protected function fetch($view_name = null) {
		$this -> view -> vars = $this -> vars;
		if ($this -> app_type == 'widget') {
			$app_name = $this -> app_name;
		} else {
			$app_name = APP_NAME;
		}
		return $this -> view -> fetch($view_name, $app_name);
	}

	protected function display($view_name = null) {
		$this -> view -> vars = $this -> vars;
		if ($this -> app_type == 'widget') {
			$app_name = $this -> app_name;
		} else {
			$app_name = APP_NAME;
		}
		$this -> view -> display($view_name, $app_name);
	}

	protected function success($info, $url = null) {
		if (empty($url)) {
			$url = get_return_url();
		}
		if (IS_AJAX) {// AJAX提交
			$data = array();
			$data['info'] = $info;
			$data['url'] = $url;
			$data['status'] = true;
			ajax_return($data);
		}

		$this -> assign('info', $info);
		$this -> assign('url', $url);
		$this -> assign('status', true);
		$this -> assign('message', $info);

		$tpl_file = 'tpl/success.html';
		$this -> display($tpl_file);
	}

	protected function error($info, $url = null) {
		if (empty($url)) {
			$url = get_return_url();
		}
		if (IS_AJAX) {// AJAX提交
			$data = array();
			$data['info'] = $info;
			$data['url'] = $url;
			$data['status'] = false;
			ajax_return($data);
		}

		$this -> assign('info', $info);
		if (empty($url)) {
			$url = get_return_url();
		}
		$this -> assign('url', $url);
		$this -> assign('status', false);
		$this -> assign('error', $info);

		$tpl_file = 'tpl/error.html';
		$this -> display($tpl_file);
	}

}
?>